<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { NButton, useMessage, NSpin, NScrollbar, NTree } from 'naive-ui'
import { sendRequest } from '@/utils/api'
import type { RoleModel } from '@/api/role'
import type { HttpResponse, HttpResponsePagination } from '@/utils/http'
import { type DicTreeModel, useDic } from '@/api/dic'
import FixedAction from '@/components/FixedAction.vue'

const message = useMessage()
const roleLoading = ref(false)
const treeLoading = ref(false)
const roleList = ref<RoleModel[]>([])
const activeId = ref<number | null>(null)
const activeName = ref<string | null>(null)
const menuOptions = ref<DicTreeModel[]>([])
const menuIdList = ref<number[]>([])
const defaultExpandedKeys = ref<number[]>([])
const isEdit = ref(false)
const updateLoading = ref(false)
const roleName = ref<string | null>(null)

// 获取菜单列表
const queryMenuOptions = async () => {
  treeLoading.value = true
  const [error, res] = await sendRequest<HttpResponse<DicTreeModel[]>>({
    module: 'sysMenu',
    api: 'getTree'
  })
  treeLoading.value = false

  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  menuOptions.value = res.data
}
// 获取角色列表
const queryRoleList = async () => {
  roleLoading.value = true
  const [error, res] = await sendRequest<HttpResponsePagination<RoleModel>>({
    module: 'role',
    api: 'list',
    override: {
      params: {
        page: 1,
        limit: 100000,
        name: roleName.value,
        roleStatus: 1
      }
    }
  })
  roleLoading.value = false

  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  roleList.value = res.data.list
  activeId.value = null
  if (res.data.list.length > 0) {
    handleActive(res.data.list[0])
  }
}
// 获取角色详情
const queryRoleInfo = async () => {
  isEdit.value = true
  const [error, res] = await sendRequest<HttpResponse<RoleModel>>({
    module: 'role',
    api: 'info',
    uri: {
      id: activeId.value as unknown as string
    }
  })

  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  const ids = useDic(menuOptions.value).getCheckedIdList(res.data.menuIdList)
  menuIdList.value = ids
  defaultExpandedKeys.value = res.data.menuIdList
}

const handleActive = (row: RoleModel) => {
  activeId.value = row.id
  activeName.value = row.roleName
  queryRoleInfo().then(() => {
    checkYueBanDisabled(row.id)
  })
}

/**
   * 机要秘书的id 32
阅办管理的id 171
机要秘书要默认勾选阅办管理并且不让取消
其余角色不让勾选阅办管理
   */
const checkYueBanDisabled = (roleId: number) => {
  setYueBanDisabled(true)
  if (roleId === 32 && !menuIdList.value.includes(171)) {
    menuIdList.value.push(171)
  }
}
const setYueBanDisabled = (disabled: boolean, data = menuOptions.value) => {
  data.forEach((item) => {
    if (item.id === 171) {
      // @ts-ignore
      item.disabled = disabled
    }
    if (item.children) {
      setYueBanDisabled(disabled, item.children)
    }
  })
}

const submit = async () => {
  const { getPathIdList } = useDic(menuOptions.value)
  updateLoading.value = true
  const [error, res] = await sendRequest({
    module: 'role',
    api: 'saveRoleMenu',
    override: {
      data: {
        id: activeId.value,
        menuIdList: getPathIdList(menuIdList.value)
      }
    }
  })
  updateLoading.value = false

  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  message.success(res.msg)
  queryRoleInfo()
}

onMounted(async () => {
  queryMenuOptions()
  queryRoleList()
})
</script>

<template>
  <div class="permission">
    <div class="permission-header">请选择您要编辑的角色权限</div>

    <div class="permission-content">
      <ul class="role-list">
        <NScrollbar style="max-height: 100%">
          <li
            v-for="item in roleList"
            :key="item.id"
            :class="activeId === item.id && 'active'"
            @click="handleActive(item)"
          >
            {{ item.roleName }}
          </li>
        </NScrollbar>
      </ul>

      <NScrollbar
        v-if="activeId"
        style="max-height: 100%; background-color: #ebeceb"
      >
        <NSpin :show="treeLoading">
          <NTree
            :data="menuOptions"
            :expanded-keys="defaultExpandedKeys"
            @update:expanded-keys="defaultExpandedKeys = $event"
            :checked-keys="menuIdList"
            @update:checked-keys="menuIdList = $event"
            key-field="id"
            label-field="name"
            block-line
            cascade
            expand-on-click
            checkable
          />
        </NSpin>
      </NScrollbar>

      <FixedAction v-if="isEdit">
        <NButton
          type="primary"
          :disabled="updateLoading"
          :loading="updateLoading"
          color="#5FB17F"
          style="width: 100rem; height: 50rem; margin: 0 auto; display: flex"
          @click="submit"
        >
          保存
        </NButton>
      </FixedAction>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.permission {
  height: 100%;
  color: rgba(0, 0, 0, 0.85);
}

.permission-header {
  height: 71rem;
  padding: 24rem 36rem 20rem;
  font-size: 16rem;
  border-bottom: 1px solid #ffffff;
}

.permission-content {
  display: flex;
  height: calc(100% - 71rem);
  gap: 0 20rem;
  padding: 20rem 20rem 100rem;
}

.role-list {
  min-width: 38%;
  height: 100%;
  padding: 15rem 20rem;
  list-style: none;
  background-color: #ebeceb;

  li {
    height: 30rem;
    text-indent: 1em;
    line-height: 30rem;
    margin-bottom: 1em;
    cursor: pointer;

    &.active {
      color: #fff;
      background-color: rgba(95, 177, 127, 0.85);
    }
  }
}
</style>
